//
//  AddTimeListVC.m
//  Doctor
//
//  Created by 阳光 on 16/10/10.
//  Copyright © 2016年 阳光. All rights reserved.
//  添加预约时间界面

#import "AddTimeListVC.h"
#import "SectionGroupModel.h"
#import "AddTimeListSectionListHeader.h"
#import "SelectAddTimeVC.h"
#import "TimeListModel.h"
#import "SelectTimeCell.h"

#import "MultipleColumnsView.h"
#import "MultipleColumnsCell.h"

static NSString *multipleColumnsCellIdentifier=@"MultipleColumnsCellIdentifier";

@interface AddTimeListVC ()<UITableViewDataSource,UITableViewDelegate,AddTimeListSectionListHeaderDelegate>

@property(nonatomic,strong)NSMutableArray *addTimeListArr;

@property(nonatomic,strong)NSMutableArray *allArr;

// 保存七天数组
@property(nonatomic,strong)NSMutableArray *sevenTimeArr;

@property(nonatomic,strong)UITableView *timeListTableView;

@property(nonatomic,assign)NSIndexPath *indexSection;

@property (nonatomic,strong) NSMutableDictionary *dataDictionary;

@end


@implementation AddTimeListVC

-(void)arrowBtnEvent:(UIButton *)btn
{
    SelectAddTimeVC *selectAddTimeVC=[SelectAddTimeVC new];
    selectAddTimeVC.sevenTimeArr=_sevenTimeArr;
    selectAddTimeVC.hospitalID=_hospitalID;
    selectAddTimeVC.timeStr=_sevenTimeArr[btn.tag];
    selectAddTimeVC.selectTimeArr=self.dataDictionary[_sevenTimeArr[btn.tag]];
    [self.navigationController pushViewController:selectAddTimeVC animated:NO];
}

// AddTimeListSectionListHeaderDelegate
-(void)didSelectTableViewHeaderFooterView
{
    [self.timeListTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"Set Video Appintment", nil);//@"添加预约时间";
    
    // 展示返回键还是菜单图标看来源
    if ([_addType isEqualToString:@"addType"])
    {
        [self initNavBarBtnItem];
    }
    
    self.dataDictionary=[NSMutableDictionary dictionary];
    
    _addTimeListArr=[NSMutableArray array];
    
    _sevenTimeArr=[NSMutableArray array];
    
    _allArr=[NSMutableArray array];
    
    [self initTableView];
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    for (int i=1;i<=7;i++)
    {
        [dateformatter setDateStyle:NSDateFormatterMediumStyle];
        [dateformatter setTimeStyle:NSDateFormatterShortStyle];
        [dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *date1 = [dateformatter stringFromDate:[NSDate date]];
        NSDate *firstTimeDate=[dateformatter dateFromString:date1];
        
        long ll= (long)[firstTimeDate timeIntervalSince1970];
        ll+=i*24*60*60;
        [dateformatter setDateFormat:@"YYYY-MM-dd"];
        NSTimeZone* timeZone = [NSTimeZone systemTimeZone];
        [dateformatter setTimeZone:timeZone];
        
        NSDate *startDate=[NSDate dateWithTimeIntervalSince1970:ll];
        [_sevenTimeArr addObject:[dateformatter stringFromDate:startDate]];
    }
    
    
    for (NSInteger i=0;i<_sevenTimeArr.count;i++)
    {
        SectionGroupModel *sectionGroupModel=[SectionGroupModel new];
        sectionGroupModel.name=_sevenTimeArr[i];
        [_addTimeListArr addObject:sectionGroupModel];
    }
    
    [self setMJRefreshTableView];
    
}

-(void)setMJRefreshTableView
{
    _timeListTableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    [_timeListTableView.mj_header beginRefreshing];
}


-(void)loadNewData
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
        
        [self getLoadData];
        dispatch_async(dispatch_get_main_queue(), ^{
            //update UI
        });
    });
}


-(void)getLoadData
{
    [_allArr removeAllObjects];
    
    // 开始时间
    NSString *startDayStr=[NSString stringWithFormat:@"%@ %@",_sevenTimeArr[0],@"00:00"];
    // 结束时间
    NSString *endDayStr=[NSString stringWithFormat:@"%@ %@",[_sevenTimeArr lastObject] ,@"23:59"];
    
    // 当医生所在医院只有一个时,直接获取
    if (![[Util getUserDefaultObjectForKey:@"ShopId"] isEqualToString:@"0"])
    {
        _hospitalID=[Util getUserDefaultObjectForKey:@"ShopId"];
    }
    
    NSDictionary *dic=@{
                        @"doctor_id":[Util getUserDefaultObjectForKey:@"id"],
                        @"shop_id":_hospitalID,
                        @"start_tag":[Util getTimeStampByDate:startDayStr],
                        @"end_tag":[Util getTimeStampByDate:endDayStr]
                        };
    
    //NSLog(@"92992--%@",dic);
    
    [QBRequest OrderTimeListWithDic:dic Success:^(id res)
     {
         NSLog(@"get--2-  --%@",res);
         
         for (NSString *val in _sevenTimeArr) {
             
             NSMutableArray *temp=[NSMutableArray array];
             for (NSDictionary *value in res[@"info"]) {
                 if ([[Util getConvertToDateByTimeStamp:value[@"start_time"]] isEqualToString:val])
                 {
                     [temp addObject:value];
                     [self.dataDictionary setObject:temp forKey:[Util getConvertToDateByTimeStamp:value[@"start_time"]]];
                 }
             }
             
             [_allArr addObject:temp];
         }
         
         
         
         NSLog(@"self.dataDictionary----%@",self.dataDictionary);
         
         [_timeListTableView reloadData];
         
         [_timeListTableView.mj_header endRefreshing];
         
     } failure:^(NSString *error) {
         
     }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // 无论七天有没有数据都显示七天
    return self.sevenTimeArr.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SectionGroupModel *sectionGroupModel=self.addTimeListArr[section];

    return sectionGroupModel.isOpen?1:0;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MultipleColumnsCell *cell=[tableView dequeueReusableCellWithIdentifier:multipleColumnsCellIdentifier];
    
    cell.indexPath=indexPath;
    cell.dataArray=self.dataDictionary[self.sevenTimeArr[indexPath.section]];
    
    // 点击触发事件
    cell.multipleColumnsView.ReturnClickItemIndex = ^(NSIndexPath * itemtIP ,NSInteger itemIndex){
      
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHt=0.0;
    NSArray *arr=self.dataDictionary[self.sevenTimeArr[indexPath.section]];
    if (arr.count!= 0)

    {
        MultipleColumnsView *cellView=[MultipleColumnsView new];
        cellView.dataArrayCount=arr.count;
        cellHt += cellView.cellHeight;
    }
    return cellHt;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return selectViewH;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    AddTimeListSectionListHeader *addTimeListSectionListHeader=[AddTimeListSectionListHeader headerView:tableView];
    addTimeListSectionListHeader.delegate=self;
    addTimeListSectionListHeader.sectionGroupModel=self.addTimeListArr[section];
    addTimeListSectionListHeader.contentView.backgroundColor=WhiteColor;
    addTimeListSectionListHeader.arrowBtn.tag=section;
    return addTimeListSectionListHeader;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setMJRefreshTableView];
}

-(void)initTableView
{
    // _timeListTableView
    _timeListTableView=[[UITableView alloc]initWithFrame:CGRectMake(0,0,APPW,APPH-selectViewH) style:UITableViewStylePlain];
    _timeListTableView.delegate=self;
    _timeListTableView.dataSource=self;
    _timeListTableView.showsVerticalScrollIndicator=NO;
    _timeListTableView.backgroundColor=MAIN_BACK_COLOR;
    _timeListTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_timeListTableView];
    _timeListTableView.tableFooterView=[UIView new];
    [_timeListTableView registerClass:[MultipleColumnsCell class] forCellReuseIdentifier:multipleColumnsCellIdentifier];
}

-(void)initNavBarBtnItem
{
    self.navigationItem.leftBarButtonItem=[UIBarButtonItem initWithNormalImage:@"back_gray" target:self action:@selector(backItemEvent)];
}

-(void)backItemEvent
{
    [self.navigationController popViewControllerAnimated:NO];
}

@end
